import {getUserInfo} from '@/api/userApi.js'
import {getList as getProducts, getExchange} from '@/api/product.js'
import {RES_PREFIX} from '@/utils/const.js'

const findSelected = (state, id)=>{
	for(let i = 0; i < state.selected.length; ++i){
		if(state.selected[i].id == id){
			return i
		}
	}
	return -1
}

const state = {
	products: [],
	selected: [],
	excharge: null
}
const getters = {
	totalPrice: state=>{
		return state.selected.reduce((sum, current)=>{
			return sum + current.excharge * current.num
		}, 0)
	}
}
const mutations = {
	setQrcode(state,qrcode){
		state.qrcode = qrcode
	},
	resetSelection(state){
		state.selected = []
	},
	setProducts(state,products){
		state.products = products.map((product)=>{
			return {
				id: product.id,
				excharge: parseInt(product.excharge),
				stock: parseInt(product.stock),
				name: product.name,
				image: `${RES_PREFIX}/images/products/${product.mid}.png`
			}
		})
	},
	setProductNum(state,payload){
		const id = payload.id
		const num = payload.num
		const excharge = payload.excharge
		
		const index = findSelected(state, id)
		//新增道具
		if(index == -1){
			if(num > 0){
				state.selected.push({id,num,excharge})
			}
			return
		}
		
		//之前有的道具，现在数量减为0了
		if(index !== -1){
			if(num <= 0){
				state.selected.splice(index, 1)
			}else {
				state.selected[index].num = num
			}
		}
	},
	setExcharge(state, excharge){
		state.excharge = excharge
	}
}

const actions = {
	fetchProducts({state,commit}){
		getProducts().then((res)=>{
			commit('setProducts', res)
		}).catch((err)=>{})
	},
	fetchExcharge({state,commit}){
		console.log('fetchExcharge')
		getExchange().then((res)=>{
			console.log('getExcharge success 1', res)
			commit('setExcharge', res)
		}).catch((err)=>{
			console.log('fetchExcharge fail', err)
		})
	}
}

export default {
	state, getters, mutations, actions
}